package com.huyna.rsspaper.service;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.R.color;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.drm.ProcessedData;
import android.graphics.Color;
import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.huyna.rsspaper.model.Article;
import com.huyna.rsspaper.parser.RssParser;
import com.huyna.rsspaper.*;

public class RssService extends AsyncTask<String, Void, List<Article>>{
	List<Article> articleList = new ArrayList<Article>();

	private Context mContext;
	private ListView mItemList;
	private TextView mTitle;
	
	public RssService(Activity context){
		mContext = context.getApplicationContext();
		//mDialog = new ProgressDialog(mContext);
		//mDialog.setMessage("Loading...");
		mItemList = (ListView)context.findViewById(R.id.itemlist);
		mItemList.setBackgroundColor(Color.BLACK);
		mTitle = (TextView)context.findViewById(R.id.title);
		mTitle.setBackgroundColor(Color.BLACK);
		mTitle.setTextColor(Color.WHITE);
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		//mDialog.show();
	}
	
	@Override
	protected List<Article> doInBackground(String... link) {
		articleList = getArticles(link);
		return articleList;
	}

	@Override
	protected void onPostExecute(List<Article> result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		updateDisplay();
		//mDialog.dismiss();
	}

	@Override
	protected void onProgressUpdate(Void... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
	}	
	
	private List<Article> getArticles(String[] link) {
		try{
			//Set up url
			URL url = new URL(link[0]);
			//Create the factory
			SAXParserFactory factory = SAXParserFactory.newInstance();
			//Create the praser
			SAXParser parser = factory.newSAXParser();
			//Create reader
			XMLReader xmlreader = parser.getXMLReader();
			//Initialize handler
			RssParser handler = new RssParser();
			//Assign handler
			xmlreader.setContentHandler(handler);
			//Get data via url
			InputSource is = new InputSource(url.openStream());
			//Perform the synchronous parse
			xmlreader.parse(is);
			//
			return handler.getArticleList();
		} catch(Exception e){
			return null;
		}
	}
	
	private void updateDisplay(){
		if(articleList == null){
			mTitle.setText("Rss not available");
			return;
		}
		
		ArrayAdapter<Article> adapter = new ArrayAdapter<Article>(mContext, android.R.layout.simple_list_item_1, articleList);
		mItemList.setAdapter(adapter);
		
	}
}
